package top.infopub.mgr.fia.web;


import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.fia.domain.OrgBudgetDomain;
import top.infopub.mgr.fia.service.OrgBudgetService;
import top.infopub.mgr.fia.vo.OrgBudgetVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.OrgInfoService;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.fia.OrgBudget;
import top.infopub.model.fia.OrgBudgetDetail;
import top.infopub.model.hr.OrgInfo;
import top.infopub.model.hr.StaffInfo;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import com.github.pagehelper.Page;
import com.google.common.collect.Maps;


/**
 * 公司年度预算管理
 * @author wangw
 * @version 2020年1月15日
 * @see OrgBudgetController
 * @since
 */
@Controller
@RequestMapping("/orgBudget")
public class OrgBudgetController extends GenericFlowController {

    @Autowired
    private OrgBudgetService orgBudgetService;

    @Autowired
    private OrgInfoService orgInfoService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    /**
     * 公司年度预算列表
     * @return
     */
    @RequestMapping("/list")
    public String list(HttpServletRequest request) {
        String bindOrgId = (String)SessionUserUtils.getSessionAttribute("bindOrgId");
        request.setAttribute("bindOrgId", bindOrgId);
        String visibleOrgIds = (String)SessionUserUtils.getSessionAttribute("visibleOrgIds");
        List<OrgInfo> orgInfos = new ArrayList<OrgInfo>();
        if (StringUtils.isEmpty(visibleOrgIds)) {
            Map<String, Object> where = Maps.newHashMap();
            where.put("state", 1);
            where.put("orderCondition", " types asc, add_time asc");
            orgInfos = orgInfoService.selectByMapWhere(where);
        }
        else {
            orgInfos = orgInfoService.selectByVisibleIds(visibleOrgIds);
        }
        request.setAttribute("orgInfos", orgInfos);
        return "fia/lay-orgBudget-list";
    }

    /**
     * 公司年度预算列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<OrgBudgetDomain> queryDataByCondition(OrgBudgetVo orgBudgetVo, ParamPage paramPage) {
        Page<OrgBudgetDomain> page = new Page<OrgBudgetDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        // 默认查询
        if(StringUtils.isEmpty(orgBudgetVo.getHrOrgBillId())){
            orgBudgetVo.setHrOrgBillId((String)SessionUserUtils.getSessionAttribute("bindOrgId"));
        }
        //查询时，结束日期增加一天
        if (orgBudgetVo.getEndDate() != null) {
            orgBudgetVo.setEndDate(DateUtils.addDays(orgBudgetVo.getEndDate(), 1));
        }
        // 因为已经设置了hrOrgBillId查询，这里不需要额外再加visibleOrgIds
        //String visibleOrgIds = (String)SessionUserUtils.getSessionAttribute("visibleOrgIds");
        //orgBudgetVo.setVisibleOrgIds(visibleOrgIds);
        page = orgBudgetService.selectPageByDomainWhere(page, orgBudgetVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 公司年度预算-新增
     * @return
     */
    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        //查询可公司年度预算的公司年度预算记录
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        String visibleOrgIds = (String)SessionUserUtils.getSessionAttribute("visibleOrgIds");
        List<OrgInfo> orgInfos = new ArrayList<OrgInfo>();
        if (StringUtils.isEmpty(visibleOrgIds)) {
            Map<String, Object> where = Maps.newHashMap();
            where.put("state", 1);
            where.put("orderCondition", " types asc, add_time asc");
            orgInfos = orgInfoService.selectByMapWhere(where);
        }
        else {
            orgInfos = orgInfoService.selectByVisibleIds(visibleOrgIds);
        }
        request.setAttribute("orgInfos", orgInfos);
        OrgInfo info = orgInfoService.selectByPrimaryKey((String)SessionUserUtils.getSessionAttribute("bindOrgId"));
        if(info != null){
            request.setAttribute("orgTypes", info.getTypes());
            request.setAttribute("billOrgName", info.getCompName());
        }
        return "fia/lay-orgBudget-add";
    }

    /**
     * 根据id查询公司年度预算详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 公司年度预算Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(String id) {
        Map<String, Object> map = new HashMap<String, Object>();
        OrgBudgetVo orgBudget = orgBudgetService.selectById(id);
        map.put("orgBudget", orgBudget);
        return new ModelAndView("fia/lay-orgBudget-detail", map);
    }

    /**
     * 新增公司年度预算
     * @return
     */
    @SuppressWarnings({"rawtypes"})
    @RequestMapping("/save")
    public @ResponseBody RspVo save(HttpServletRequest request, OrgBudgetVo orgBudget) {
        if(StringUtils.isEmpty(orgBudget.getOrgTypes()) || StringUtils.isEmpty(orgBudget.getBillOrgName()) 
            || StringUtils.isEmpty(orgBudget.getHrStaffApplyId())){
            return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("当前账号未绑定公司");
        }
        if (StringUtils.isBlank(orgBudget.getId())) {
            int count = orgBudgetService.count(orgBudget.getBelongsYear(),orgBudget.getHrOrgBillId());
            //判断是否存在同一公司名称、同一预算年度已有生效中单据
            if (count > 0) {
                return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("已有同一公司同一预算年度单据，不可重复提交");
            }
        }

        String[] months = request.getParameterValues("months");//子项月份
        String[] manageFees = request.getParameterValues("manageFee");//子项-管理费用
        String[] saleFees = request.getParameterValues("saleFee");//子项-营销费用
        String[] selfCaes = request.getParameterValues("selfCae");//子项-自行承接建安额

        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();

        /**
         * 公司年度预算主表处理
         */
        String id = IdFactory.getUUIDUpper();
        orgBudget.setId(id);
        orgBudget.setHrStaffApplyId(vo.getHrStaffId());
        orgBudget.setAddBy(vo.getId());
        orgBudget.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String codes = codeGeneratorConfigService.generatorCode("fia_org_budget_codes");
        orgBudget.setCodes(codes);
        // 处理processId
        //orgBudget.setProcessId(IdFactory.getUUIDUpper());
        orgBudget.setProcessStatus("9");//生效中
        orgBudget.setUptBy(vo.getId());
        orgBudget.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        //子项处理
        List<OrgBudgetDetail> orgBudgetDetails = new ArrayList<OrgBudgetDetail>();
        for (int i = 0; i < months.length; i++ ) {
            String orderId = months[i];
            OrgBudgetDetail orgBudgetDetail = new OrgBudgetDetail();
            String subId = IdFactory.getUUIDUpper();//自动生成主键
            orgBudgetDetail.setId(subId);
            orgBudgetDetail.setOrgBudgetId(id);
            orgBudgetDetail.setMonths(Integer.parseInt(orderId));
            orgBudgetDetail.setManageFee(new BigDecimal(manageFees[i]));
            orgBudgetDetail.setSaleFee(new BigDecimal(saleFees[i]));
            orgBudgetDetail.setSelfCae(new BigDecimal(selfCaes[i]));
            orgBudgetDetail.setAddBy(vo.getId());
            orgBudgetDetail.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
            orgBudgetDetails.add(orgBudgetDetail);
        }

        orgBudgetService.addOrgBudget(orgBudget, orgBudgetDetails);
        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD,
            "公司年度预算 -新增公司年度预算：公司名=" + orgBudget.getBillOrgName(), null);
        return RspVo.getSuccessResponse();
    }

    /**
     * 修改公司年度预算状态
     * @param 
     * @return 
     * @see
     */
    @RequestMapping("/updateStatus")
    public @ResponseBody RspVo<String> updateStatus(String id) {
        OrgBudget budget = orgBudgetService.selectByPrimaryKey(id);
        String oldStatus = budget.getProcessStatus();
        String newStatus = "9";
        if ("9".equals(oldStatus)) {
            newStatus = "10";
        }
        else {
            newStatus = "9";
        }
        budget.setProcessStatus(newStatus);
        budget.setUptTime(new Date());
        budget.setUptBy(SessionUserUtils.getSessionUserId());
        orgBudgetService.updateBySelective(budget);
        // 操作日志
        LogUtil.bizLog(
            LogUtil.LogModelType.OTHER,
            LogUtil.AcctionType.UPDATE,
            "修改状态  公司年度预算表单据ID:" + budget.getCodes(), "");
        return RspVo.getSuccessResponse();
    }

    /**
     * 编辑公司费用预算表
     * @param payBillVo
     * @return 
     * @throws NoSuchMethodException 
     * @throws InvocationTargetException 
     * @throws IllegalAccessException 
     * @see
     */
    @RequestMapping("/update")
    public @ResponseBody RspVo<OrgBudgetVo> update(OrgBudgetVo orgBudgetVo) {
        orgBudgetService.udpOrgBudget(orgBudgetVo);
        LogUtil.bizLog(LogModelType.OTHER, AcctionType.UPDATE, "修改公司费用预算表 - 公司费用预算表Id:"
                                                               + orgBudgetVo.getId(), null);
        return RspVo.getSuccessResponse(orgBudgetVo);
    }

}
